import 'package:flutter/material.dart';

class ListViewDemo extends StatefulWidget {
  const ListViewDemo({super.key});

  @override
  State<ListViewDemo> createState() => _ListViewDemoState();
}

class _ListViewDemoState extends State<ListViewDemo> {
  final ScrollController _scrollController = ScrollController();
  final List<String> _items = [];
  int _page = 0;
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    _loadData();
    _scrollController.addListener(_scrollListener);
  }

  void _scrollListener() {
    if (_scrollController.position.pixels >
        _scrollController.position.maxScrollExtent - 200) {
      _loadData();
    }
  }

  Future<void> _loadData() async {
    if (_isLoading) return;
    setState(() => _isLoading = true);

    // 模拟网络请求延迟
    await Future.delayed(const Duration(seconds: 1));

    // 生成20条模拟数据
    final newItems = List.generate(
      20,
      (i) => '第${_page + 1}页 项目${_items.length + i + 1}',
    );

    setState(() {
      _items.addAll(newItems);
      _page++;
      _isLoading = false;
    });
  }

  Future<void> _refresh() async {
    setState(() {
      _page = 0;
      _items.clear();
    });
    await _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        controller: _scrollController,
        slivers: [
          // 悬浮标题
          SliverAppBar(
            title: const Text('高级列表演示'),
            pinned: true,
            expandedHeight: 200,
            flexibleSpace: FlexibleSpaceBar(
              background: Image.network(
                'https://picsum.photos/2000',
                fit: BoxFit.cover,
              ),
            ),
          ),

          // 下拉刷新组件
          SliverToBoxAdapter(
            child: RefreshIndicator(
              onRefresh: _refresh,
              child: _buildListContent(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildListContent() {
    return Column(
      children: [
        // 固定列表头
        const Padding(
          padding: EdgeInsets.all(16),
          child: Text('商品列表', style: TextStyle(fontSize: 20)),
        ),

        // 固定高度列表主体
        SizedBox(
          height: MediaQuery.of(context).size.height - 200,
          child: ListView.separated(
            itemCount: _items.length + 1,
            separatorBuilder: (_, i) => const Divider(),
            itemBuilder: (context, index) {
              if (index < _items.length) {
                return ListTile(
                  title: Text(_items[index]),
                  trailing: const Icon(Icons.chevron_right),
                );
              }
              return _buildProgressIndicator();
            },
          ),
        ),
      ],
    );
  }

  Widget _buildProgressIndicator() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Center(
        child:
            _isLoading
                ? const CircularProgressIndicator()
                : const Text('没有更多数据了~'),
      ),
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }
}
